package ids;

public class DistributedId {

    /**
     *
     * @param time 41位
     * @param shardId 10位
     * @param seq 12位
     * @return
     */
    public static long buildId(long time, int shardId, long seq) {
        return seq + (shardId << 12) + (time << 22);
    }

    public static long[] parseId(long id) {
        long time = id >>> 22;
        long shardId = (id & (1023 << 12)) >>> 12;
        long seq = id & 4095;
        return new long[]{time, shardId, seq};
    }

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        int shardId = 32;
        int seq = 2334;

        long id = buildId(time, shardId, seq);
        System.out.println(String.format("生成Id条件，时间：%s，机器号：%s，序列号：%s，生成Id：%s", time, shardId, seq, id));

        long[] parseId = parseId(id);
        System.out.println(String.format("根据id【%s】转换结果，时间：%s，机器号：%s，序列号：%s", id, parseId[0], parseId[1], parseId[2]));
    }
}
